package m6;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RPCServer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //连接 rabbitmq
        ConnectionFactory f = new ConnectionFactory();
        f.setHost("192.168.64.140");
        // 5672 端口，客户端应收发消息的端口
        // 15672 端口。管理控制台界面的访问端口
        f.setPort(5672);
        f.setUsername("admin");
        f.setPassword("admin");
        Connection con = f.newConnection();
        Channel c = con.createChannel();  //通信的通道
        //创建调用队列，rpc_queue
        c.queueDeclare("rpc_queue", false, false, false,null);
        //从 rpc_queue 接收调用信息
        c.basicConsume("rpc_queue", true, (consumerTag,message) ->{
            //  1.n  2.返回队列名  3.关联id
            String s = new String(message.getBody());
            Integer n = Integer.valueOf(s);

            String replyTo = message.getProperties().getReplyTo();

            String cid = message.getProperties().getCorrelationId();
            //调用fnnq（n）得到斐波那契数
            String result = String.valueOf(fbnq(n));
            //向客户端发回结果,携带关联id
            AMQP.BasicProperties props = new AMQP.BasicProperties.Builder().correlationId(cid).build();
            c.basicPublish("", replyTo, props,result.getBytes());
        }, (consumerTag) -> {});

    }
    //求第n个斐波那契数
    static long fbnq(int n){
        //1 1 2 3 5 8 13 21
        if(n == 1 || n == 2){
            return 1L;
        }
        return fbnq(n-1)+fbnq(n-2);
    }
}
